package cn.manager.travel.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//@WebFilter("/*")
public class LoginFilter implements Filter {
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
		HttpServletRequest req = (HttpServletRequest) request;
		
		//1.获取资源的请求路径
		String uri = req.getRequestURI();
		//2.判断是否包含登录相关资源
		if (uri.contains("/login.jsp") || uri.contains("/admin/login") ||  uri.contains("/css/") ||  uri.contains("/js/")){
			//包含,放行
			chain.doFilter(req,response);
		}else {
			//不包含,需要用户登录验证
			//3.从session获取user
			Object user = req.getSession().getAttribute("user");
			if(user != null){
				//登录了,放行
				chain.doFilter(req,response);
			}else {
				//跳转到登录页面
				req.setAttribute("error", "你尚未登录,请登录后再进行其他操作");
				req.getRequestDispatcher("/login.jsp").forward(req,response);
			}
		}
    }
	
	public void init(FilterConfig config) throws ServletException {
	}
	
	public void destroy() {
	}
	
}
